// -----------------------------------------------------------------------------
// This source file is part of Matrix Platform
// 	(Universal .NET Software Development Platform)
// For the latest info, see http://www.matrixplatform.com
// 
// Copyright (c) 2009-2010, Ingenious Ltd
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Matrix.Common.Extended;
using Matrix.Common.FrontEnd;
using Matrix.Common.Sockets.Common;
using Matrix.Common.Sockets.NetworkTracer;
using Matrix.Common.Core;

namespace Matrix.Common.Diagnostics.FrontEnd.TracerControls
{
    /// <summary>
    /// 
    /// </summary>
    public partial class SourcesTracerControl : UserControl
    {
        NetworkTracer _tracer = null;

        public NetworkTracer Tracer
        {
            get
            {
                return _tracer;
            }

            set
            {
                if (_tracer != null)
                {
                    _tracer = null;
                }

                _tracer = value;
                if (value != null)
                {
                    value.TracerNetUpdateEvent += new NetworkTracer.TracerNetUpdateDelegate(value_TracerNetUpdateEvent);
                }

                WinFormsHelper.BeginManagedInvoke(this, UpdateUI);
            }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public SourcesTracerControl()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            UpdateUI();
        }

        void UpdateUI()
        {
            NetworkTracer tracer = _tracer;
            
            listViewSources.Enabled = tracer != null;
            toolStripSources.Enabled = tracer != null;
            toolStripServer.Enabled = tracer != null;

            if (tracer == null)
            {
                listViewSources.Items.Clear();
                return;
            }

            toolStripButtonServer.Checked = tracer.IsServerStarted;
            if (tracer.IsServerStarted)
            {
                toolStripButtonServer.Text = "Stop";
                toolStripButtonServer.Image = Matrix.Common.FrontEnd.Properties.Resources.PDA;
            }
            else
            {
                toolStripButtonServer.Image = null;
                toolStripButtonServer.Text = "Start";
            }

            listViewSources.Items.Clear();
            foreach (SocketCommunicator comm in tracer.Clients)
            {
                ListViewItem item = new ListViewItem(listViewSources.Groups["Servers"]);
                SetItemAsCommunicator(item, comm);
                listViewSources.Items.Add(item);
            }

            foreach (SocketCommunicator comm in tracer.ServerClients)
            {
                ListViewItem item = new ListViewItem(listViewSources.Groups["Clients"]);
                SetItemAsCommunicator(item, comm);
                listViewSources.Items.Add(item);
            }
        }

        protected void SetItemAsCommunicator(ListViewItem item, SocketCommunicator comm)
        {
            item.Text = comm.IsConnected.ToString();
            item.SubItems.Add(StringHelper.ToStringSafe(comm.EndPoint));
            item.Tag = comm;
        }

        void value_TracerNetUpdateEvent(NetworkTracer tracer)
        {
            WinFormsHelper.BeginManagedInvoke(this, UpdateUI);
        }

        protected override void OnResize(EventArgs e)
        {
            toolStripTextBoxAddress.Width = this.Width - 170;
            base.OnResize(e);
        }

        private void toolStripButtonAdd_Click(object sender, EventArgs e)
        {
            NetworkTracer tracer = _tracer;
            if (tracer == null)
            {
                return;
            }

            string addressString = toolStripTextBoxAddress.Text;
            //if (string.IsNullOrEmpty(addressString))
            //{// Empty, try local host.
            //    addressString = "127.0.0.1";
            //}

            if (addressString.Contains(":"))
            {
                addressString = addressString.Split(':')[0];
            }

            IPAddress address;
            if (IPAddress.TryParse(addressString, out address) == false)
            {
                MessageBox.Show("Invalid address.");
                return;
            }

            if (_tracer.StartTraceListen(new IPEndPoint(address, NetworkTracer.DefaultPort)) == false)
            {
                MessageBox.Show("Failed to start listener at address.");
                return;
            }
        }

        private void toolStripTextBoxAddress_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButtonAdd_Click(sender, EventArgs.Empty);
            }
        }

        private void toolStripButtonRemove_Click(object sender, EventArgs e)
        {
            NetworkTracer tracer = _tracer;
            if (tracer == null)
            {
                return;
            }

            foreach (ListViewItem item in listViewSources.SelectedItems)
            {
                if (item.Group == listViewSources.Groups["Servers"])
                {
                    EndPoint endPoint = ((SocketCommunicator)item.Tag).EndPoint;
                    if (endPoint != null)
                    {
                        tracer.StopTraceListen((IPEndPoint)endPoint);
                    }
                }
                else if (item.Group == listViewSources.Groups["Clients"])
                {
                    tracer.DisconnectTraceServerClient((SocketCommunicator)item.Tag);
                }
            }
        }

        private void toolStripButtonServer_Click(object sender, EventArgs e)
        {
            NetworkTracer tracer = _tracer;
            if (tracer == null)
            {
                return;
            }

            if (toolStripButtonServer.Checked)
            {
                tracer.StartTraceServer(NetworkTracer.DefaultPort);
            }
            else
            {
                tracer.StopTraceServer();
            }
        }
    }
}
